﻿/*
    Parker for Kaixin001.com 

    Copyright (C) 2008, TurboZV, turbozv@gmail.com, http://www.turbozv.com/

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    *KEEP THIS HEADER INFORMATION*
*/

// by xzsong.seu@gmail.com, 2008-09-20
using System;
using System.Collections.Generic;
using Helper;
using System.Collections.ObjectModel;
using System.Net.Json;

namespace Parker
{
    class CarAutoHelper
    {
        private HttpHelper _hh;
        private string _verifyCode;
        private UserConfigData _userConfigData;
        private CarPoolManager _carPoolManagerManager;

        public CarAutoHelper(HttpHelper httpHelper, UserConfigData userConfigData, string verifyCode)
        {
            _hh = httpHelper;
            _verifyCode = verifyCode;
            _userConfigData = userConfigData;

            bool bFromFile = false;
            _carPoolManagerManager = SerializeHelper.Deserialize<CarPoolManager>(out bFromFile);
            if (!bFromFile)
            {
                RetriveCarPool();
            }
        }

        private bool BuyCar(int carId)
        {
            string content = _hh.Post("http://www.kaixin001.com/parking/purchase.php", "verify=" + _verifyCode + "&carid=" + carId + "&color=" + _userConfigData.CarColor + "&_=");
            content = _hh.Get("http://www.kaixin001.com/parking/purchase.php?verify=" + _verifyCode + "&action=1&carid=" + carId + "&color=" + _userConfigData.CarColor);
            string sub = ContentHelper.GetMidString(content, "display:block", "确定");
            if (sub.IndexOf("购买了") > -1)
            {
                TraceLog.PrintLn(ContentHelper.GetMidString(sub, "<strong>", "</strong>"));
                return true;
            }
            return false;
        }

        public bool AutoBuyAndUpgrade(int cash, Collection<CarInfo> oldCars, JsonArrayCollection seatList)
        {
            bool bUpdate = false;  // 返回值，表示是否做了　买车/买车位/升级　操作

            if (_userConfigData.DoAutoUpgradeGarage)
            {
                bUpdate = UpgradeGarage(ref cash, seatList);
            }

            // 整理旧车信息
            Dictionary<string, int> existingCars = new Dictionary<string, int>();
            foreach (CarInfo carInfo in oldCars)
            {
                if (!existingCars.ContainsKey(carInfo.CarName))
                {
                    existingCars.Add(carInfo.CarName, carInfo.Id);
                }
            }

            // auto buy
            int count = Math.Min(_userConfigData.DoAutoMaxCarNumber, 10) - oldCars.Count;
            if (count > 0)   // 车辆数是否已达用户设定的上限？
            {
                // 计算出该买哪几辆新车，并更新现金数量
                List<int> carsToBuy = _carPoolManagerManager.GetBuyCarIdList(_userConfigData.NoBuyCarIdList, existingCars, count, ref cash);
                foreach (int carId in carsToBuy)
                {
                    if (BuyCar(carId))
                    {
                        bUpdate = true;
                    }
                    else
                    {
                        break;
                    }
                }
                return bUpdate;  // todo: 买完车后其实还可以试着升级车，继续执行 // by hook.hu@gmail.com 2008-09-23
            }

            // auto upgrade
            if (_userConfigData.DoAutoUpgradeCar > 0)
            {
                List<KeyValuePair<int, int>> carsToUpgrade = _carPoolManagerManager.GetUpdateCarIdPairList(_userConfigData.NoUpgradeCarIdList, existingCars, ref cash, _userConfigData.DoAutoUpgradeCar == 2);
                foreach (KeyValuePair<int, int> upgradePair in carsToUpgrade)
                {
                    if (UpgradeCar(existingCars, upgradePair))
                    {
                        bUpdate = true;
                    }
                    else
                    {
                        break;
                    }
                }
                return bUpdate;
            }

            return bUpdate;
        }

        // todo: 对是否成功未加判断，请注意  // by hook.hu@gmail.com 2008-09-23
        private bool UpgradeCar(Dictionary<string, int> existingCars, KeyValuePair<int, int> upgradePair)
        {
            string content = string.Format("verify={0}&carid={1}&color={3}&oldcarid={2}", _verifyCode, upgradePair.Key, upgradePair.Value,_userConfigData.CarColor);
            TraceLog.PrintLn("升级车辆 {0} => {1}",
                _carPoolManagerManager.GetExistingCarName(upgradePair.Value, existingCars),
                _carPoolManagerManager.GetCarName(upgradePair.Key));
            string result = _hh.Post("http://www.kaixin001.com/parking/updatecar.php", content);
            return true;
        }        

        // 从开心获得所有汽车的信息
        private void RetriveCarPool()
        {
            bool bHasMore = false;
            int index = 0;
            do
            {
                bHasMore = false;
                string content = _hh.Get("http://www.kaixin001.com/~parking/market.php?start=" + index);
                int pos = 0;
                string startPos=ContentHelper.GetMidString(content,"<table class=\"cheshi\">","<tr>",out pos);
                if(pos > -1)
                {
                    content = content.Substring(pos);
                    do
                    {
                        NewCarInfo newCarInfo = new NewCarInfo();
                        newCarInfo.CarName = ContentHelper.GetMidString(content, "align=\"absmiddle\" />", "</div>", out pos);                        
                        newCarInfo.CarPrice = ContentHelper.GetMidInteger(content, "价格：", "元", out pos);
                        newCarInfo.CarId = ContentHelper.GetMidInteger(content, "purchase(", ")", out pos);
                        if (newCarInfo.IsValid && pos > -1)
                        {
                            _carPoolManagerManager.AddNewCar(newCarInfo);
                            bHasMore = true;
                            content = content.Substring(pos);
                        }
                        else
                        {
                            break;
                        }
                    } while (true);
                }
                index = index + 8;  // +8 翻下一页
            } while (bHasMore);            
            _carPoolManagerManager.Save();
        }

        // todo: 对是否成功未加判断，请注意  // by hook.hu@gmail.com 2008-09-23
        private bool BuyUseCard(int cardId, int price)
        {
            string verifyContent = string.Format("verify={0}&cardid={1}", _verifyCode, cardId);
            _hh.Post("http://www.kaixin001.com/parking/buycard.php", verifyContent);
            string actionContent = string.Format("http://www.kaixin001.com/parking/buycard.php?verify={0}&action=1&cardid={1}", _verifyCode, cardId);
            string result = _hh.Post("http://www.kaixin001.com/parking/card_resetpark.php", verifyContent);
            return true;
        }

        private bool UpgradeGarage(ref int cash, JsonArrayCollection seatList)
        {
            if (_userConfigData.DoAutoUpgradeGarage && cash > 30000)
            {
                foreach (JsonObjectCollection seat in seatList)
                {
                    int parkId = JsonHelper.GetIntegerValue(seat["parkid"]);
                    if (((parkId >> 16) & 0xff) == 1)
                    {
                        if (BuyUseCard(15, 30000))
                        {
                            cash -= 30000;  // 买车位成功，扣去 30000 元   // by hook.hu@gmail.com 2008-09-24
                            TraceLog.PrintLn("升级免费车位成功，花费 30000 元");
                            return true;
                        }
                    }
                }
            }
            return false;
        }
    }
}
